﻿#include <sb.h>

bool g_usetry = false;

kpointer _thd(kpointer ptr)
{
	kAsyncList* al = (kAsyncList*)ptr;

	for (;;)
	{
		if (g_usetry)
		{
			kpointer data;

			while ((data = k_aslq_try(al)) != NULL)
			{
				kint n = K_CAST_PTR_TO_INT(data);
				k_mesgf("mesg -> %d\n", n);

				if (n == 255)
					return NULL;
			}

			k_sleep(100);
		}
		else
		{
			/*
			kTimeVal tv;
			k_timeval_now(&tv);
			k_timeval_add_milli(&tv, 100);
			*/

			kpointer data = k_aslq_pop_wait(al, 100);
			if (data)
			{
				kint n = K_CAST_PTR_TO_INT(data);
				k_mesgf("mesg -> %d\n", n);

				if (n == 255)
					break;
			}
		}
	}

	return NULL;
}

int main(void)
{
	k_mesg("ASYNC LIST TEST\n\n");

	kAsyncList* al = k_aslq_new();
	kThread* thd = k_thread_new(_thd, al, 0, 0);
	k_thread_start(thd);

	for (;;)
	{
		char sz[260];
		gets_s(sz);

		if (sz[0] == 'q')
		{
			k_aslq_push(al, K_CAST_INT_TO_PTR(255));
			break;
		}

		switch (sz[0])
		{
			case 'z':
				k_aslq_enter(al);
				k_aslq_push_nolock(al, K_CAST_INT_TO_PTR(2));
				k_aslq_push_nolock(al, K_CAST_INT_TO_PTR(22));
				k_aslq_push_nolock(al, K_CAST_INT_TO_PTR(222));
				k_aslq_leave(al);
				break;

			case 'x':
				k_aslq_push(al, K_CAST_INT_TO_PTR(3));
				k_aslq_push(al, K_CAST_INT_TO_PTR(33));
				k_aslq_push(al, K_CAST_INT_TO_PTR(333));
				break;

			case 'c':
				k_aslq_push(al, K_CAST_INT_TO_PTR(4));
				break;
		}
	}

	k_thread_delete(thd);
	k_aslq_delete(al);

	return 0;
}

